package com.liming.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.liming.po.News;
import com.liming.po.NewsMessage;
import com.liming.po.TextMessage;
import com.thoughtworks.xstream.XStream;

public class MessageUtil {

	// 定义MsgType为常量
	// 普通消息
	public static final String MESSAGE_TEXT = "text"; // 文本消息
	public static final String MESSAGE_IMAGE = "image"; // 图片消息
	public static final String MESSAGE_VOICE = "voice"; // 语音消息
	public static final String MESSAGE_VIDEO = "video"; // 视频消息
	public static final String MESSAGE_SHORTVIDEO = "shortvideo"; // 小视频信息
	public static final String MESSAGE_LOCATION = "location"; // 位置消息,这里开发文档中MsgType微event，通过Debug发现实为location
	public static final String MESSAGE_LINK = "link"; // 链接消息
	public static final String MESSAGE_NEWS = "news"; // 图文消息
	// 事件推送
	public static final String MESSAGE_EVENT = "event"; // 事件消息
	public static final String MESSAGE_EVENT_SUBSCRIBE = "subscribe"; // 订阅
	public static final String MESSAGE_EVENT_UNSUBSCRIBE = "unsubscribe"; // 取消订阅
	// 自定义菜单事件推送
	public static final String MESSAGE_CLICK = "CLICK"; // 点击菜单
	public static final String MESSAGE_VIEW = "VIEW"; // 点击跳转链接
	public static final String MESSAGE_SCANCODE = "scancode_push"; // 点击扫码事件

	/**
	 * xml转为Map
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException {
		Map<String, String> map = new HashMap<String, String>();

		// 用SAXReader解析xml
		SAXReader reader = new SAXReader();

		// 从request获取输入流
		InputStream ins = req.getInputStream();
		Document doc = reader.read(ins);

		// 获取根目录
		Element root = doc.getRootElement();
		List<Element> list = root.elements();

		// 遍历
		for (Element e : list) {
			map.put(e.getName(), e.getText());
		}

		// 关闭流
		ins.close();

		return map;
	}

	/**
	 * 将文本消息对象转为XML
	 * 
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessage textMessage) {
		XStream xstream = new XStream();
		// 将根节点替换为xml
		xstream.alias("xml", textMessage.getClass());

		return xstream.toXML(textMessage);
	}

	// 拼接文本消息
	public static String initText(String fromUserName, String toUserName, String content) {
		TextMessage text = new TextMessage();
		text.setToUserName(fromUserName);
		text.setFromUserName(toUserName);
		text.setMsgType(MessageUtil.MESSAGE_TEXT);
		text.setCreateTime((int) new Date().getTime());
		text.setContent(content);

		return textMessageToXml(text);
	}

	/**
	 * 订阅事件
	 * 
	 * @return
	 */
	public static String subscribeMsg() {
		StringBuffer sb = new StringBuffer();
		sb.append("当你发现一本很好很好的书，你要明白这书总有一天你会看完，你要做的是超越这本书;\n");
		sb.append("当你发现一个很好很好的知识分享平台，你要明白，随着你的成长，总有一天你会离开;\n");
		sb.append("当你遇到一个很好的老师，你要明白，总有一天你要超越他,他并不一定全对,而你能做的只有默默感恩;\n");
		sb.append("这个世界有很多方式能够实现自己的价值，这些之所以还没有消亡，说明还不断有人处于我们以前的懵懂阶段。粉过之后，才有成长，才能默默地离开。\n");
		sb.append("回复数字获取更多：\n");
		sb.append("1.网易云音乐地铁戳心评论(文本消息);\n");
		sb.append("2.开心一刻;(文本消息)\n");
		sb.append("3.妹子图;(单图文消息)\n");
		sb.append("4.妹子图;(多图文消息)\n");
		sb.append("回复？查看菜单。");

		return sb.toString();
	}

	/**
	 * 主菜单
	 * 
	 * @return
	 */
	public static String menuText() {
		StringBuffer sb = new StringBuffer();
		sb.append("【菜单】\n");
		sb.append("1.网易云音乐地铁戳心评论(文本消息);\n");
		sb.append("2.开心一刻;(文本消息)\n");
		sb.append("3.妹子图;(单图文消息)\n");
		sb.append("4.妹子图;(多图文消息)\n");
		sb.append("回复？查看菜单。");

		return sb.toString();
	}

	/**
	 * 1号随机菜单 随机向用户发送一条网易云音乐评论
	 * 
	 * @return
	 */
	public static String sendWangYi() {
		StringBuffer sb = new StringBuffer();

		Random ran = new Random();

		int a = ran.nextInt(10);
		if (a == 0) {
			sb.append("究竟是有多喜欢  才会温柔成这个样子\n");
			sb.append("来自小名叫七月\n");
			sb.append("在刘若英《很爱很爱你》下方的评论");
		} else if (a == 1) {
			sb.append("我不喜欢这世界，我只喜欢你\n");
			sb.append("来自Air暴雪\n");
			sb.append("在张悬《宝贝》下方的评论");
		} else if (a == 2) {
			sb.append("最怕一生碌碌无为，还说平凡难能可贵。\n");
			sb.append("来自昂翌\n");
			sb.append("在白亮/赵静《孙大剩》下方的评论");
		} else if (a == 3) {
			sb.append("多少人以朋友的名义默默的爱着\n");
			sb.append("来自月海浪花\n");
			sb.append("在陈奕迅《十年》下方的评论");
		} else if (a == 4) {
			sb.append("祝你们幸福是假的，祝你幸福是真的\n");
			sb.append("来自似是而非或是世事可畏\n");
			sb.append("在好妹妹乐队《我到外地去看你》下方的评论");
		} else if (a == 5) {
			sb.append("你别皱眉，我走就好\n");
			sb.append("来自hhn呀\n");
			sb.append("在刘若英《很爱很爱你》下方的评论");
		} else if (a == 6) {
			sb.append("十年前你说生如夏花般绚烂，	十年后你说平凡才是唯一的答案\n");
			sb.append("\n");
			sb.append("");
		} else if (a == 7) {
			sb.append("你那么孤独，却说一个人真好\n");
			sb.append("来自——数的绵羊都睡了\n");
			sb.append("在丁可《if》下方的评论");
		} else if (a == 8) {
			sb.append("哭着吃过饭的人，是能够走下去的\n");
			sb.append("来自---___________---\n");
			sb.append("在Doughnuts Hole《おとなの掟》下方的评论");
		} else if (a == 9) {
			sb.append("我听过一万首歌，\n");
			sb.append("看过一千部电影，读过一百本书，\n");
			sb.append("却从未俘获一个人的心\n");
			sb.append("来自rajorA\n");
			sb.append("在陈粒《奇妙能力歌》下方的评论");
		}

		return sb.toString();
	}

	// 2.笑话
	public static String sendJOKE() throws JSONException {
		StringBuilder sb = new StringBuilder();
		TianAPIUtil tianAPI = new TianAPIUtil();
		JSONArray jsonArray = tianAPI.request(tianAPI.JOKE, "");
		JSONObject jsonObject = jsonArray.getJSONObject(0);
		// content 处理
		String content = jsonObject.getString("content");
		sb.append("【" + jsonObject.get("title") + "】\n");
		sb.append(DateDisposeUtil.replaceStr(content, "<br/>", "").toString());

		return sb.toString();
	}

	// 图片
	public static String sendAnImg() throws JSONException {
		StringBuilder sb = new StringBuilder();

		TianAPIUtil tianAPI = new TianAPIUtil();

		JSONArray jsonArray = tianAPI.request(tianAPI.MEINV, "&num=1");
		JSONObject jsonObject = null;
		// 只发送一张图片
		jsonObject = jsonArray.getJSONObject(0);
		String picUrl = jsonObject.getString("picUrl");

		sb.append(picUrl);

		return sb.toString();
	}

	/**
	 * 将图文消息对象转为XML
	 * 
	 * @param newsMessage
	 * @return
	 */
	public static String newsMessageToXml(NewsMessage newsMessage) {
		XStream xstream = new XStream();
		// 将根节点替换为xml
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new News().getClass());

		return xstream.toXML(newsMessage);
	}

	// 拼接图文消息
	// 3.单图文消息
	public static String initNewsMessage(String fromUserName, String toUserName) throws JSONException {
		String message = null;
		NewsMessage newsMessage = new NewsMessage();
		List<News> newsList = new ArrayList<News>();

		// item
		// 利用天行API发送美女图文消息
		TianAPIUtil tianAPI = new TianAPIUtil();

		JSONArray jsonArray = tianAPI.request(tianAPI.MEINV, "&num=1");
		JSONObject jsonObject = null;
		News news = new News();

		jsonObject = jsonArray.getJSONObject(0);
		String title = jsonObject.getString("title");
		String description = jsonObject.getString("description");
		String picUrl = jsonObject.getString("picUrl");

		news.setTitle(title);
		news.setDescription(description);
		news.setPicUrl(picUrl);
		news.setUrl(picUrl);
		newsList.add(news);

		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime((int) new Date().getTime());
		newsMessage.setMsgType(MessageUtil.MESSAGE_NEWS);
		newsMessage.setArticleCount(newsList.size());
		newsMessage.setArticles(newsList);

		return newsMessageToXml(newsMessage);
	}

	// 4.多图文消息
	public static String initMoreNewsMessage(String fromUserName, String toUserName) throws JSONException {
		String message = null;
		NewsMessage newsMessage = new NewsMessage();
		List<News> newsList = new ArrayList<News>();

		// item
		// 利用天行API发送美女图文消息
		TianAPIUtil tianAPI = new TianAPIUtil();

		JSONArray jsonArray = tianAPI.request(tianAPI.MEINV, "&num=4");
		JSONObject jsonObject = null;

		for (int i = 0; i < jsonArray.length(); i++) {
			News news = new News();
			jsonObject = jsonArray.getJSONObject(i);
			String title = jsonObject.getString("title");
			String description = jsonObject.getString("description");
			String picUrl = jsonObject.getString("picUrl");

			news.setTitle(title);
			news.setDescription(description);
			news.setPicUrl(picUrl);
			news.setUrl(picUrl);

			newsList.add(news);
		}

		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime((int) new Date().getTime());
		newsMessage.setMsgType(MessageUtil.MESSAGE_NEWS);
		newsMessage.setArticleCount(newsList.size());
		newsMessage.setArticles(newsList);

		return newsMessageToXml(newsMessage);
	}

}
